package dao

import (
	"gin-demo/common"
	"gin-demo/entity"
)

type UserDao interface {
	GetUserById(id int64) (*entity.User, error)
	GetUserRoles(id int64) (*[]string, error)
}

type userDaoImpl struct{}

func NewUserDao() UserDao {
	return &userDaoImpl{}
}

func (u *userDaoImpl) GetUserById(id int64) (*entity.User, error) {
	db := common.MysqlDB()
	var user entity.User
	db = db.Debug().Select("id", "username", "create_time").Table("user").Where("id", id).Find(&user)
	if db.Error != nil {
		return nil, db.Error
	} else if db.RowsAffected == 0 {
		return nil, nil
	}
	return &user, nil
}

func (u *userDaoImpl) GetUserRoles(id int64) (*[]string, error) {
	db := common.MysqlDB()
	var roles []string
	db = db.Debug().Select("r.role_code").Table("role r").Joins("join user_role ur on ur.role_id = r.id").Where("ur.user_id = ?", id).Find(&roles)
	if db.Error != nil {
		return nil, db.Error
	}
	return &roles, nil
}
